package com.cheboohui.iqs.spider.pingan.price;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cheboohui.iqs.common.basic.StringUtil;
import com.cheboohui.iqs.common.basic.TimeUtil;
import com.cheboohui.iqs.config.Config;
import com.cheboohui.iqs.http.tool.HttpClient;
import com.cheboohui.iqs.menu.ErrorNews;
import com.cheboohui.iqs.spider.login.LoginEntity;
import com.cheboohui.iqs.spider.pingan.BeforePolicyPingAn;
import com.cheboohui.iqs.spider.pingan.CheckCarPingAn;
import com.cheboohui.iqs.spider.pingan.entity.DutyFree;
import com.cheboohui.iqs.spider.pingan.entity.PAResult;
import com.cheboohui.iqs.spider.pingan.price.get.Paramten;
import com.cheboohui.iqs.spider.pingan.price.get.PramtenTwo;
import com.cheboohui.iqs.spring.entity.Car;
import com.cheboohui.iqs.spring.entity.Insurance;
import com.cheboohui.iqs.spring.entity.Policy;
import com.cheboohui.iqs.spring.entity.Price;
import com.cheboohui.iqs.spring.entity.PriceOther;
import com.cheboohui.iqs.spring.entity.price.request.PriceRequest;
import com.cheboohui.iqs.spring.entity.price.response.CheckCarResult;
import com.cheboohui.iqs.spring.entity.price.response.PriceResult;

/**
 * 平安爬虫报价系统
 * 
 * @author xielonghai
 *
 */
public class PriceStep {
	/**
	 * logger:日志工具.
	 */
	private Log log = LogFactory.getLog(PriceStep.class);

	/**
	 * calc_url : (平安报价地址)
	 */
	private final String calc_url = "https://icorepnbs.pingan.com.cn/icore_pnbs/do/app/quotation/applyQueryAndQuote";

	/**
	 * 平安登录标识
	 */
	private LoginEntity login;

	/**
	 * 平安保费计算请求参数类
	 */
	private PriceRequest priceRequest;

	/**
	 * 平安车辆查询结果
	 */
	private PAResult checkCar;

	/**
	 * 请求报价车险列表
	 */
	private List<Insurance> insuranceList;

	/**
	 * 平安报价步骤构造器
	 * 
	 * @param priceRequest
	 * @param login
	 */
	public PriceStep(PriceRequest priceRequest, LoginEntity login) {
		String licenceNo = priceRequest.getLicense().getLicenceNo();
		this.priceRequest = priceRequest;
		this.priceRequest.getLicense().setLicenceNo(licenceNo.substring(0, 2) + "-" + licenceNo.substring(2));
		this.login = login;
		this.insuranceList = priceRequest.getInsuranceList();
		if (!login.isState())
			this.checkCar = new PAResult(ErrorNews.L02, "登录平安系统失败,未获取得到验证码");
		else {
			this.checkCar = CheckCarPingAn.getCarByLabel(priceRequest.getCar(), login);/** 车辆查询 */
			setDefault();
			// dealPolicy();
		}
	}

	/**
	 * 保单查询处理
	 */
	public void dealPolicy() {
		JSONObject bp = BeforePolicyPingAn.checkPolicyByFrameNo(priceRequest.getLicense().getFrameNo(), login);
		log.info(bp.getString("msg"));

		switch (bp.getIntValue("type")) {
		case 0:// 没有发现以往保单信息
			other.setRenewalTra("02");
			log.info(login.getOrderNo() + ",没有发现以往保单信息,开始车辆查询....");
			/** 车辆查询 */
			this.checkCar = CheckCarPingAn.getCarByLabel(priceRequest.getCar(), login);
			return;
		case 3:
			log.info(login.getOrderNo() + ",发现以往保单信息....");
			dealPolicyInsurance(bp);
			return;
		default:
			this.checkCar = new PAResult(ErrorNews.L03, "平安爬虫往年保单查询出现错误:" + bp.getString("msg"));
			return;
		}
	}

	private void dealPolicyInsurance(JSONObject bp) {
		switch (bp.getJSONObject("tra").getIntValue("type")) {
		case 0:// 无该险的保单
			other.setRenewalTra("02");
			tra = false;
			break;
		case 1:// 已经购买保险
			deleteTra();
			tra = false;
			break;
		case 2:// 保险到期大于等于90天
			deleteTra();
			tra = false;
			break;
		case 4:// 保险到期小于90天
			tra = findIns("TP");
			other.setRenewalTra("01");
			other.setEndTraTime(bp.getJSONObject("tra").getJSONObject("data").getJSONObject("policy")
					.getString("insuranceEndTime"));
			other.setEndTraDay(
					-bp.getJSONObject("tra").getJSONObject("data").getJSONObject("policy").getIntValue("eday"));
			traBeginTime = bp.getJSONObject("tra").getString("bTime");
			break;
		default:
			tra = findIns("TP");
			other.setRenewalTra("03");
			traBeginTime = TimeUtil.timeNextDay("yyyy-MM-dd") + " 00:00:00";
			break;
		}

		switch (bp.getJSONObject("bus").getIntValue("type")) {
		case 0:// 无该险的保单
			other.setRenewalBus("02");
			bus = false;
			break;
		case 1:// 已经购买保险
			bus = false;
			deleteBus();
			break;
		case 2:// 保险到期大于等于90天
			bus = false;
			deleteBus();
			break;
		case 4:// 保险到期小于90天
			bus = findIns("BTR");
			other.setRenewalBus("01");
			other.setEndBusTime(bp.getJSONObject("bus").getJSONObject("data").getJSONObject("policy")
					.getString("insuranceEndTime"));
			other.setEndBusDay(
					-bp.getJSONObject("bus").getJSONObject("data").getJSONObject("policy").getIntValue("eday"));
			busBeginTime = bp.getJSONObject("bus").getString("bTime");
			break;
		default:
			bus = findIns("BTR");
			other.setRenewalBus("03");
			busBeginTime = TimeUtil.timeNextDay("yyyy-MM-dd") + " 00:00:00";
			break;
		}

		if (bus || tra) {
			JSONObject data = null;
			if (bus) {
				data = bp.getJSONObject("bus").getJSONObject("bus");
			} else {
				data = bp.getJSONObject("tra").getJSONObject("tra");
			}

			if (null != data)
				this.checkCar = new PAResult(data.getJSONObject("autoModelType"));
			else
				this.checkCar = CheckCarPingAn.getCarByLabel(priceRequest.getCar(), login);/** 车辆查询 */
		} else {
			this.checkCar = new PAResult(ErrorNews.B17, "重复投保");
		}
	}

	private boolean findIns(String code) {
		for (Insurance i : insuranceList) {
			if (i.getCode().equals(code))
				return true;
		}
		return false;
	}

	private void deleteBus() {
		for (Insurance i : priceRequest.getInsuranceList()) {
			if (!i.getCode().equals("TP")) {
				priceRequest.getInsuranceList().remove(i);
				return;
			}
		}
	}

	private void deleteTra() {
		for (Insurance i : priceRequest.getInsuranceList()) {
			if (i.getCode().equals("TP")) {
				priceRequest.getInsuranceList().remove(i);
				return;
			}
		}
	}

	/**
	 * 车辆查询结果
	 * 
	 * @return
	 */
	public PAResult getCheckCar() {
		return checkCar;
	}

	private boolean bus = false;// 商业险选择标志
	private String busBeginTime;// 商业险起保时间

	private boolean tra = false;// 交强险选择标志
	private String traBeginTime;// 交强险起保时间

	private DutyFree dutyfree = new DutyFree(false);// 免税标志

	private int priceNum = 1;// 保费计算次数

	/** 起保时间的初始变量设定 */
	private void setDefault() {
		int to = 1;
		for (Insurance i : priceRequest.getInsuranceList()) {
			if (i.getCode().equals("TP")) {
				tra = true;
				traBeginTime = i.getBeginTime();
				to++;
			} else if (i.getCode().equals("BTR")) {
				bus = true;
				busBeginTime = i.getBeginTime();
				to++;
			}
			if (to > 2)
				break;
		}

		if (StringUtil.isNulls(busBeginTime))
			busBeginTime = TimeUtil.timeNextDay("yyyy-MM-dd") + " 00:00:00";
		if (StringUtil.isNulls(traBeginTime))
			traBeginTime = TimeUtil.timeNextDay("yyyy-MM-dd") + " 00:00:00";
		log.info(login.getOrderNo() + ",起保时间的初始变量设定结束....");
	}

	private JSONObject request;// 报价请求json

	private JSONObject response;// 报价返回json

	private PAResult stepResult = new PAResult(null);// 保费计算过程中信息

	private PriceResult result = null;// 平安报价返回结果

	private boolean priceTo = false;// 报价是否结束

	/**
	 * 报价并获取报价结果
	 * 
	 * @return
	 */
	public PriceResult getPriceResult() {
		if (priceTo) {
			return getResult();
		} else {
			PAResult pri = toPrice();
			priceTo = true;
			if (!pri.isState()) {
				if (null != result)
					return result;
				else {
					PriceResult res = new PriceResult(pri.getError(), pri.getErrorValue());
					if (ErrorNews.B01.equals(pri.getError()))
						res.setResult(new Price(CheckCarPingAn.toResult(checkCar.getCarList())));
					return res;
				}

			} else
				return getResult();
		}
	}

	/**
	 * 进入保费计算
	 * 
	 * @return
	 */
	private PAResult toPrice() {
		if (!stepResult.isState())
			return stepResult;

		if (1 == priceNum) {// 是否为初次保费计算
			log.info(login.getOrderNo() + ",进入平安爬虫报价正式开始....");
			if (!getParamtenFirst())
				return stepResult;

			if (!dealCar()) {
				if (null == result)
					return stepResult;
				else
					return new PAResult(ErrorNews.L03, "");
			} else
				return toPriceTwo();

		} else if (priceNum > 14) {
			log.error(login.getOrderNo() + ",平安循环爬虫报价次数超过14次,自动停止该次报价,请查错....");
			return new PAResult(ErrorNews.L03, "平安循环爬虫报价次数超过14次,自动停止该次报价,请查错....");
		} else {
			return toPriceTwo();
		}
	}

	private boolean tax = true;// 需?进行车辆免税判断

	/**
	 * 进入保费计算第二步
	 * 
	 * @return
	 */
	private PAResult toPriceTwo() {
		this.next = true;

		if (tra) {// 交强险
			if (!toPrice_tra())
				return stepResult;
		}

		if (bus) {// 商业险
			if (!toPrice_bus())
				return stepResult;
		}

		if (next && RequestJudge.judge(response, 0))// 报价成功跳出口
			return new PAResult(null);
		else {
			if (priceType(!next)) {
				return toPrice();
			} else {
				return stepResult;
			}
		}
	}

	/**
	 * 选择报价方式
	 * 
	 * @param type
	 * @return
	 */
	private boolean priceType(boolean type) {
		if (type)
			return getParamtenFirst();
		else
			return getPramtenTwo();
	}

	/** 下一步报价 */
	private boolean next = true;
	/** 确定是否已经确定交强险时间了 **/
	private boolean tra2 = true;
	/** 确定是否已经确定商业险时间了 **/
	private boolean bus2 = true;

	/**
	 * 在选择交强险情况下处理相关结果及参数后报价
	 * 
	 * @return
	 */
	private boolean toPrice_tra() {
		if (tax) {
			dutyfree = ChangeVehicleTaxInfo.judgeVeh(response);
			if (dutyfree.isState()) {
				other.setTax(true);
				log.info(login.getOrderNo() + ",该报价车辆是免税车................");
				this.tax = false;
				this.next = false;
			}
		}

		if (tra2) {
			/** 交强险到期时间 **/
			String timetra = TimeDeal.getTime_tra(response).trim();
			if (null != timetra && !"".equals(timetra)) {
				this.tra2 = false;
				if (null != timetra && "tra".equals(timetra)) {
					log.error(login.getOrderNo() + ",该报价车辆交强险保险重复投保。。。");
					stepResult = new PAResult(ErrorNews.B04, "该报价车辆交强险保险重复投保");
					return stepResult.isState();
				}
				log.info(login.getOrderNo() + ",该报价车辆的交强险保险到期时间:" + timetra);

				int day = TimeDeal.timeInterval(timetra);
				if (day >= Config.ToDay) {
					stepResult = new PAResult(ErrorNews.B04, "该报价车辆交强险保险到期时间大于90天，请你在90天以内在来投保,到期天数:" + day + "天");
					return stepResult.isState();
				}
				log.info(login.getOrderNo() + ",该报价车辆的交强险保险到期天数:" + day);
				if (other.getEndTraDay() <= 0)
					other.setEndTraDay(day);

				if (day == -1) {
					log.error(login.getOrderNo() + ",该报价车辆的交强险保险到期时间<获取天数错误。。。>:" + timetra);
				}

				if (!timetra.equals(traBeginTime)) {
					this.traBeginTime = timetra;
					next = false;
				}
			}
		}
		return true;
	}

	/**
	 * 在选择商业险情况下处理相关结果及参数后报价
	 * 
	 * @return
	 */
	private boolean toPrice_bus() {
		if (bus2) {
			/*** 商业险到期时间 ***/
			String timebus = TimeDeal.getTime(response);
			if (null != timebus && !"".equals(timebus)) {
				this.bus2 = false;
				log.info(login.getOrderNo() + ",该报价车辆的商业险保险到期时间:" + timebus);
				int day = TimeDeal.timeInterval(timebus);
				if (day >= Config.ToDay) {
					stepResult = new PAResult(ErrorNews.B04, "该报价车辆商业险保险到期时间大于90天，请你在90天以内在来投保,到期天数:" + day + "天");
					return stepResult.isState();
				}
				log.info(login.getOrderNo() + ",该报价车辆的商业险保险到期天数:" + day);
				if (other.getEndBusDay() <= 0)
					other.setEndBusDay(day);
				if (day == -1) {
					log.error(login.getOrderNo() + ",该报价车辆的商业险保险到期时间<获取天数错误。。。>:" + timebus);
				}

				if (!timebus.equals(busBeginTime)) {
					this.busBeginTime = timebus;
					next = false;
				}
			}
		}
		return true;
	}

	/**
	 * 车型判断
	 * 
	 * @return
	 */
	private boolean dealCar() {
		log.info(login.getOrderNo() + ",判断选择车型与平台返回的车型是否一致........");

		JSONArray vehiclePriceList = response.getJSONObject("applyQueryResult").getJSONArray("vehiclePriceList");
		if (null != vehiclePriceList && !vehiclePriceList.isEmpty() && vehiclePriceList.size() > 0) {
			checkCar.setCarList(vehiclePriceList);
			log.info(login.getOrderNo() + ",报价返回中存在车型列表........");
			for (int k = 0; k < vehiclePriceList.size(); k++) {
				if (checkCar.getObj().getDoubleValue("purchasePrice") == vehiclePriceList.getJSONObject(k)
						.getDoubleValue("purchasePrice")) {
					log.info(login.getOrderNo() + ",报价返回中存在车型列表....找到选择车型");
					return true;
				}
			}
			stepResult = new PAResult(ErrorNews.B01, "选择车型与平台返回的车型不一致");
			return false;
		}

		JSONObject carDeal = RequestJudge.carJudge(response, checkCar.getObj().getString("autoModelCode"));
		if (carDeal.getBoolean("state")) {
			if (null == carDeal.getString("autoModelCode") || "".equals(carDeal.getString("autoModelCode").trim())) {
				log.info(login.getOrderNo() + ",车型判断出错。。。。。。。。。。。。。。。。。。");
				stepResult = new PAResult(ErrorNews.L03, "车型判断出错，请后台查看...");
				return false;
			}

			log.info(login.getOrderNo() + ",。。。。。。。选择车型与平台返回的车型不一致:" + carDeal.getString("autoModelCode"));
			CheckCarResult checkCar = CheckCarPingAn.getCarByLabel(carDeal.getString("autoModelCode"), login);
			if (checkCar.isState()) {
				result = new PriceResult(ErrorNews.B01, "选择车型与平台返回的车型不一致:" + carDeal.getString("autoModelCode"));

				result.setResult(new Price(checkCar.getResult()));

				return false;
			} else {
				log.info(login.getOrderNo() + ",平台返回车型查询出错-----------查询返回：" + JSONObject.toJSONString(checkCar));
				result = new PriceResult(ErrorNews.L03, "平台返回车型查询出错：" + checkCar.getDetailedValue());
				return false;
			}
		}

		log.info(login.getOrderNo() + ",选择车型与平台返回的车型一致........");
		return true;
	}

	/**
	 * 初次请求参数设定
	 */
	private boolean getParamtenFirst() {
		JSONObject obj = new JSONObject();
		obj.put("tra", tra);
		obj.put("bus", bus);
		obj.put("busBeginTime", busBeginTime);
		obj.put("traBeginTime", traBeginTime);
		obj.put("car", checkCar.getObj());

		obj.put("dutyfree", dutyfree.isState());
		if (dutyfree.isState())
			obj.put("result", JSONObject.parseObject(dutyfree.getResult()));

		this.request = Paramten.oneGetPraten(login.getOrderNo(), priceRequest, obj);

		if (null == request || request.isEmpty()) {
			stepResult = new PAResult(ErrorNews.L03, "按初次请求参数设定错误，参数请求返回null");
		}
		log.info(login.getOrderNo() + ",按初次请求参数设定结束....:" + stepResult.isState());
		if (stepResult.isState())
			return httpToPingAn();
		else
			return stepResult.isState();
	}

	/**
	 * 再次请求参数设定
	 */
	private boolean getPramtenTwo() {
		// if (dealPriceCarList())
		// return getParamtenFirst();
		// else if (carDate) {
		// stepResult = new PAResult(ErrorNews.C02, "报价后平安返回车型列表中无所选车型");
		// return stepResult.isState();
		// } else {
		if(bus2 || tra2)
			this.request = PramtenTwo.changeParamOne(request, response, checkCar.getObj().getDouble("purchasePrice"));
		else
			this.request = PramtenTwo.changeParamTwo(request, response, checkCar.getObj().getDouble("purchasePrice"));
		
		if (null == request || request.isEmpty()) {
			stepResult = new PAResult(ErrorNews.L03, "再次请求参数设定错误，参数请求返回null");
		}
		
		log.info(login.getOrderNo() + ",再次请求参数设定结束....:" + stepResult.isState());
		if (stepResult.isState())
			return httpToPingAn();
		else
			return stepResult.isState();
		// }
	}

	private boolean dpcl = true;
	private boolean carDate = false;

	/**
	 * 判断报价返回车型处理
	 * 
	 * @return
	 */
	private boolean dealPriceCarLists() {
		if (dpcl) {
			try {
				JSONArray vehiclePriceList = response.getJSONObject("applyQueryResult")
						.getJSONArray("vehiclePriceList");
				if (null != vehiclePriceList && !vehiclePriceList.isEmpty() && vehiclePriceList.size() > 0) {
					checkCar.setCarList(vehiclePriceList);

					JSONArray p = new JSONArray();

					for (int k = 0; k < vehiclePriceList.size(); k++) {
						if (checkCar.getObj().getDoubleValue("purchasePrice") == vehiclePriceList.getJSONObject(k)
								.getDoubleValue("purchasePrice")) {
							this.dpcl = false;
							return false;
						}

						if (checkCar.getObj().getDoubleValue("exhaustMeasure") == vehiclePriceList.getJSONObject(k)
								.getDoubleValue("exhaustMeasure")
								&& checkCar.getObj().getIntValue("seats") == vehiclePriceList.getJSONObject(k)
										.getIntValue("seats"))
							p.add(vehiclePriceList.getJSONObject(k));

					}

					if (!p.isEmpty() && p.size() > 0) {
						JSONObject one = p.getJSONObject(0);
						for (int k = 0; k < p.size(); k++) {
							if (one.getDoubleValue("purchasePrice") > p.getJSONObject(k)
									.getDoubleValue("purchasePrice"))
								one = p.getJSONObject(k);
						}
						checkCar.setObj(one);
						this.dpcl = false;
						return true;
					} else {
						carDate = true;
						return false;
					}

				} else
					return false;
			} catch (Exception e) {
				log.info(login.getOrderNo() + ",判断报价返回车型处理response:" + response);
				log.info(login.getOrderNo() + ",判断报价返回车型处理异常:" + e);
				return false;
			}
		} else
			return false;
	}

	/**
	 * 报价请求
	 * 
	 * @return
	 */
	private boolean httpToPingAn() {
		try {
			if (null == request || request.isEmpty()) {
				stepResult = new PAResult(ErrorNews.L03, "报价请求错误，参数请求为null");
				return stepResult.isState();
			}

			log.info(
					login.getOrderNo() + ",第" + priceNum + "次向平安爬虫报价开始....request:" + JSONObject.toJSONString(request));
			String res = HttpClient._httpPostToBody_json(login.getHttpClient(), login.getHttpContext(), calc_url,
					JSONObject.toJSONString(request));
			log.info(login.getOrderNo() + ",第" + priceNum + "次向平安爬虫报价结束,response:" + res);

			try {
				response = JSONObject.parseObject(res);

				if (!valResponse()) {
					return false;
				}

				priceNum++;
				return stepResult.isState();
			} catch (Exception e) {
				log.error(login.getOrderNo() + ",平安爬虫报价后转化JSON异常:" + e);
				log.error(login.getOrderNo() + ",平安爬虫报价返回结果:" + res);
				stepResult = new PAResult(ErrorNews.L03, "平安爬虫报价后转化JSON异常:" + e.getMessage());
				return stepResult.isState();
			}

		} catch (Exception e) {
			log.error(login.getOrderNo() + ",平安爬虫报价出现异常:" + e);
			log.error(login.getOrderNo() + ",平安爬虫报价请求参数:" + request);
			stepResult = new PAResult(ErrorNews.L03, "平安爬虫报价出现异常:" + e.getMessage());
			return stepResult.isState();
		}
	}

	private boolean valResponse() {
		JSONObject applyQueryResult = response.getJSONObject("applyQueryResult");

		log.info(login.getOrderNo() + ",第" + priceNum + "次平安爬虫报价返回errorMessage:"
				+ applyQueryResult.getString("errorMessage"));

		/** 2017-06-14 下午-----豪车不承保问题 **/
		if (RequestJudge.judge(response, 1)) {
			try {
				JSONObject decisionTreeResult = response.getJSONObject("c01CaculateResult")
						.getJSONObject("c01ResultDTO").getJSONObject("decisionTreeResult");
				if ("0".equals(decisionTreeResult.getString("isQuote"))) {
					stepResult = new PAResult(ErrorNews.L05,
							// "决策树不报价原因:" +
							decisionTreeResult.getString("noQuoteReason")
					// +";决策树修改建议:"+decisionTreeResult.getString("modifyAdvise")
					);
					log.info(login.getOrderNo() + ",第" + priceNum + "次平安爬虫报价请求参数:" + stepResult.getErrorValue());
					return stepResult.isState();
				}
			} catch (Exception e) {
				log.error(login.getOrderNo() + ",平安爬虫报价--判断豪车不承保问题时出现异常:" + e);
				log.error(login.getOrderNo() + ",平安爬虫报价返回:" + response);
				stepResult = new PAResult(ErrorNews.L03, "平安爬虫报价--判断豪车不承保问题时出现异常:" + e.getMessage());
				return stepResult.isState();
			}
		}

		if (!"0".equals(applyQueryResult.getString("errorCode"))) {

			log.error(login.getOrderNo() + ",第" + priceNum + "次平安爬虫报价请求参数:" + request);
			log.info(login.getOrderNo() + ",第" + priceNum + "次平安爬虫报价返回结果:" + response);

			if ("1".equals(applyQueryResult.getString("errorCode"))
					&& applyQueryResult.getString("errorMessage").indexOf("过户") > 0) {
				stepResult = new PAResult(ErrorNews.B18, "errorMessage:" + applyQueryResult.getString("errorMessage"));
			} else
				stepResult = new PAResult(ErrorNews.L03, "平安爬虫报价返回错误:" + applyQueryResult.getString("errorMessage"));

			return false;
		} else
			return true;
	}

	/** 车险报价后其他信息返回类 **/
	private PriceOther other = new PriceOther();
	/** 保单信息实体类 **/
	private Policy policy = new Policy();

	/**
	 * 报价返回信息
	 * 
	 * @return
	 */
	private PriceResult getResult() {
		log.info(login.getOrderNo() + ",初步确定平安爬虫报价成功后返回response:" + response);
		if (RequestJudge.judge(response, 1)) {
			log.error(login.getOrderNo() + ",经核实平安爬虫报价没有成功----没有保存订单号！！！！！！");
			return new PriceResult(ErrorNews.L03, "经核实平安爬虫报价没有成功----没有保存订单号！");
		}
		if (!RequestJudge.judge(response, 0)) {
			log.error(login.getOrderNo() + ",经核实平安爬虫报价出现未定义错误，请查看！！！！！！");
			return new PriceResult(ErrorNews.L03, "经核实平安爬虫报价出现未定义错误--请查看！");
		}

		List<Insurance> list = new ArrayList<>();

		policy.setOrderNo(login.getOrderNo());

		if (bus) {
			JSONObject c01ResultDTO = response.getJSONObject("c01CaculateResult").getJSONObject("c01ResultDTO");
			
			if(null==c01ResultDTO.getJSONObject("decisionTreeResult") || StringUtil.isEmpty(c01ResultDTO.getJSONObject("decisionTreeResult").getString("quotationNo"))){
				policy.setBusinessNo(response.getJSONObject("c01CaculateResult").getString("quotationNo"));
			}else{
				policy.setBusinessNo(c01ResultDTO.getJSONObject("decisionTreeResult").getString("quotationNo"));
			}
			
			policy.setBusinessTotal(c01ResultDTO.getDouble("totalActualPremium"));
			JSONArray busList=c01ResultDTO.getJSONArray("dutyList");
			if(null==busList || busList.isEmpty())
				busList=response.getJSONObject("voucher").getJSONArray("c01DutyList");
			
			list = BeforePolicyPingAn.getBusList(busList);
			if (null != list && !list.isEmpty()) {
				for (Insurance i : list) {
					i.setBeginTime(busBeginTime);
					i.setEndTime(TimeUtil.timeNextYear(busBeginTime, TimeUtil.DEFAULT_TIME));
				}
			}
			if (StringUtil.isNulls(other.getEndBusTime()))
				other.setEndBusTime(busBeginTime);
		}

		if (tra) {
			JSONObject c51ResultDTO = response.getJSONObject("c51CaculateResult").getJSONObject("c51ResultDTO");

			if(null==c51ResultDTO.getJSONObject("decisionTreeResult") || StringUtil.isEmpty(c51ResultDTO.getJSONObject("decisionTreeResult").getString("quotationNo"))){
				policy.setTraficNo(response.getJSONObject("c51CaculateResult").getString("quotationNo"));
			}else{
				policy.setTraficNo(c51ResultDTO.getJSONObject("decisionTreeResult").getString("quotationNo"));
			}
			
			policy.setTrafic(c51ResultDTO.getDouble("totalActualPremium"));// 交强险
			
			JSONObject vehicleTaxInfoDTO=c51ResultDTO.getJSONObject("vehicleTaxInfoDTO");
			if(null==vehicleTaxInfoDTO||vehicleTaxInfoDTO.isEmpty())
				vehicleTaxInfoDTO=response.getJSONObject("voucher").getJSONObject("vehicleTaxInfo");
			policy.setTax(vehicleTaxInfoDTO.getDouble("totalTaxMoney"));
			policy.setCode("01");
			policy.setCodeValue("算费成功");

			Insurance i = new Insurance();
			i.setCode("TP");
			i.setValue("交强险");
			i.setPrice(c51ResultDTO.getDouble("totalActualPremium"));
			i.setBeginTime(c51ResultDTO.getString("insuranceBeginTime"));
			i.setEndTime(c51ResultDTO.getString("insuranceEndTime"));

			list.add(i);
			if (StringUtil.isNulls(other.getEndTraTime()))
				other.setEndTraTime(traBeginTime);
		}

		other.setActualPrice(ComputeCar.compute(checkCar.getObj().getDoubleValue("purchasePrice"),
				priceRequest.getLicense().getRegisteredTime(), busBeginTime));

		policy.setTotal();
		Price price = new Price(policy, list);
		price.setOther(other);

		Car car = new Car();

		String dsc = checkCar.getObj().getString("vehicleDesc");
		if (StringUtil.isNulls(dsc))
			dsc = checkCar.getObj().getString("remark");
		car.setAutoModelCode(checkCar.getObj().getString("autoModelCode"));
		car.setExhaustMeasure(checkCar.getObj().getDoubleValue("exhaustMeasure"));
		car.setCarType(sub(dsc));
		car.setPurchase(checkCar.getObj().getDoubleValue("purchasePrice"));
		car.setSeats(checkCar.getObj().getIntValue("seats"));
		car.setLabelNo(checkCar.getObj().getString("autoModelName"));
		String year = checkCar.getObj().getString("marketDate");
		if (StringUtil.isNulls(year))
			year = checkCar.getObj().getString("firstSaleDate");
		car.setYear(year);
		car.setModels(dsc);
		price.setCar(car);

		log.info(login.getOrderNo() + ",平安爬虫报价成功......");
		return new PriceResult(price);
	}

	private static String sub(String org) {
		if (StringUtil.isNulls(org))
			return "";
		if (org.indexOf("版") > 0) {
			String or = org.substring(0, org.indexOf("版") + 1);
			System.out.println(or);
			while (or.indexOf(" ") > 0) {
				or = or.substring(or.indexOf(" ") + 1).trim();
			}
			return or;
		} else
			return "";
	}
}
